﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Commons.Collections;
using Workflow.Common.FileUtil;
using Workflow.Common.mail;
using Workflow.Common.Tools;
using Workflow.Dto;
using Workflow.IService;
using Workflow.Model;
using Workflow.Model.Enum;
using Workflow.Resource;
using Workflow.Service;
using Workflow.Web.Common;
using NVelocity;
using NVelocity.App;
using Workflow.Common;


namespace Workflow.Web.Controllers
{
	[Localization]
	[UserAuthorize]
	public class TIFFController : Controller
	{
		//
		// GET: /TIFF/
		public ICaseEEMService CaseEEMService { get; set; }

		public IWorkStatusService WorkStatusService { get; set; }
		public IUserManager UserManager { get; set; }
		public IApplicatService ApplicatService { get; set; }

		public IPaymentService PaymentService { get; set; }

		public ICaseReasonService CaseReasonService { get; set; }

		

		#region EEM
		public ActionResult IndexEEM()
		{
			string caseNo = Request["caseNo"];
			string nextCaseKeepStatus = Request["NextCaseKeepStatus"];

			if (string.IsNullOrEmpty(caseNo))
			{
				ViewData["content"] = Global.NoCaseMessage;
				ViewData["Case"] = new CaseEEM();
				return View("GPEEMViewTiff");
			}
			var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
			var tifBasePath = ConfigurationManager.AppSettings["TifBasePath_View"];
			string file = tifBasePath + model.GetFolerPathEN() + model.FileName + ".tif";
			// string file = Request["file"];
            file = Server.UrlEncode(file);
            string fcontent = "<iframe id='tiffframe'    frameborder='0'  src=' /" + ConfigReader.TiffPage + "?file=" + file + "' style='width:100%;height:100%;'></iframe>";
			ViewData["content"] = fcontent;
			ViewData["Case"] = model;
			if (nextCaseKeepStatus == null)
			{
				ViewData["NextCaseKeepStatus"] = model.WorkStatus.WorkStatusCode;
			}
			else
			{
				ViewData["NextCaseKeepStatus"] = nextCaseKeepStatus;
			}


			return View("GPEEMViewTiff");
		}
		[HttpPost]
		public ActionResult FinishCaseEEM()
		{
			try
			{
				var invoiceNo = Request["InvoiceNo"];
				var caseNo = Request["caseNo"];
				var comment = Request["StatusComment"];
				var finishFlag = Request["FinishFlag"];

				var invoiceNoPl = Request["InvoiceNoPL"];
				var paymentPL = Request["PaymentPL"];
				
				var payment = Request["Payment"];
				

				String nextCaseKeepStatus = Request["NextCaseKeepStatus"];
				ViewData["NextCaseKeepStatus"] = nextCaseKeepStatus;

				var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
				
				if (finishFlag == "3")//PL work
				{
					model.InvoiceNo = invoiceNoPl;
					
					model.StatusComment = comment;

					if (string.IsNullOrEmpty(paymentPL))
					{
						if (model.CaseMapPropertyEEM == null)
						{
							var caseMap = new CaseMapPropertyEEM();
							caseMap.CaseEEM = model;
							model.CaseMapPropertyEEM = caseMap;
						}
						model.CaseMapPropertyEEM.Payment = null;
					}
					else
					{
						var tempPayment = PaymentService.GetPaymentById(paymentPL);
						if (model.CaseMapPropertyEEM == null)
						{
							var caseMap = new CaseMapPropertyEEM();
							caseMap.CaseEEM = model;
							model.CaseMapPropertyEEM = caseMap;
						}
						model.CaseMapPropertyEEM.Payment = tempPayment;
					}

					CaseEEMService.SaveOrUpdateCaseNoLog(model);
				}
				else //PA WORK
				{
					var userid = Session[ConfigReader.AuthorizeSessionUserID];
					var user = UserManager.GetUser(Int64.Parse(userid.ToString()));

					if (model.Operator == user)
					{
						if (finishFlag == "1") //check one
						{
							model.InvoiceNo = invoiceNo;

							if (string.IsNullOrEmpty(payment))
							{
								if (model.CaseMapPropertyEEM == null)
								{
									var caseMap = new CaseMapPropertyEEM();
									caseMap.CaseEEM = model;
									model.CaseMapPropertyEEM = caseMap;
								}
								model.CaseMapPropertyEEM.Payment = null;
							}
							else
							{
								var tempPayment = PaymentService.GetPaymentById(payment);
								if (model.CaseMapPropertyEEM == null)
								{
									var caseMap = new CaseMapPropertyEEM();
									caseMap.CaseEEM = model;
									model.CaseMapPropertyEEM = caseMap;
								}
								model.CaseMapPropertyEEM.Payment = tempPayment;
							}

						}
						//状态变为Closed以后，希望依旧保留最后一次Pending时的理由，方便日后查找
						//model.CommentCode = null;

						var nowStatus = model.WorkStatus.WorkStatusCode;
						model.WorkStatus = WorkStatusService.GetWorkStatus(GetNextStatus(nowStatus));
						model.StatusDate = ToolsHelper.GetTimeZoneNow();

						if (model.WorkStatus.WorkStatusCode != ((int) EnumWorkStatus.Closed).ToString())
						{
							model.Operator = user.NextStepUser;
							model.StatusOperator = user;
						}
						//model.StatusOperator = user; when case close than eem1 is check one and eem2 is check two
						if (!string.IsNullOrEmpty(comment))
						{
							model.StatusComment = model.StatusComment + "[" + comment + ":" + model.WorkStatus.WorkStatusNameEEM + "]";
						}

						CaseEEMService.SaveOrUpdateCase(model);
					}
				}


				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.ActiveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		[HttpPost]
		public ActionResult RejectCaseEEM()
		{
			try
			{
				var comment = Request["StatusComment"];
				var caseNo = Request["caseNo"];
				var CommentCode = Request["RejectReason"];
				var invoiceNo = Request["InvoiceNo"];
				var finishFlag = Request["FinishFlag"];
				var email = Request["email"];
				var chkMail = Request["chkMail"];
				string nextCaseKeepStatus = Request["NextCaseKeepStatus"];
				ViewData["NextCaseKeepStatus"] = nextCaseKeepStatus;


				var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
				
				var nowStatus = model.WorkStatus.WorkStatusCode;
				//var status = (int)EnumWorkStatus.Reject;
				model.WorkStatus = WorkStatusService.GetWorkStatus(GetPreviousStatus(nowStatus));
				model.StatusDate = ToolsHelper.GetTimeZoneNow();
				var userid = Session[ConfigReader.AuthorizeSessionUserID];
				var user = UserManager.GetUser(Int64.Parse(userid.ToString()));
				if (!string.IsNullOrEmpty(comment))
				{
					model.StatusComment = model.StatusComment + "[" + comment + ":" + model.WorkStatus.WorkStatusNameEEM + "]" ;
				}
			
				if(finishFlag=="1")
				{
					model.CommentCode = CaseReasonService.GetRejectReasonById(CommentCode);
					model.Operator = null;
					model.InvoiceNo = invoiceNo;
					if (chkMail == "on")
					{
						if (!String.IsNullOrEmpty(email))
						{
							var applicat = ApplicatService.GetApplicatByMail(email);

							MailInfoDto mailInfoDto = new MailInfoDto();

							mailInfoDto.sendTo = applicat.Name;
							mailInfoDto.comment = ReplaceComment(comment);

							var body = GetEmailTemplateString(mailInfoDto, "SendMail_EEM.htm");

							this.SendMail(applicat.Email, body); //发mail
						}
					}
				}
				else if ((finishFlag == "2"))
				{
					model.CommentCode = null;
					model.Operator = model.StatusOperator;
				}
				model.StatusOperator = user;


				CaseEEMService.SaveOrUpdateCase(model);
				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.ActiveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		[HttpPost]
		public ActionResult QACaseEEM()
		{
			try
			{
				var comment = Server.UrlDecode(Request["StatusComment"]);
				var caseNo = Request["caseNo"];
				var CommentCode = Request["PengdingReason"];
				var invoiceNo = Request["InvoiceNo"];
				var email = Request["email"];
				var chkMail = Request["chkMail"];
				string nextCaseKeepStatus = Request["NextCaseKeepStatus"];
				ViewData["NextCaseKeepStatus"] = nextCaseKeepStatus;


				if (chkMail == "on")
				{
					if (!String.IsNullOrEmpty(email))
					{
						var applicat = ApplicatService.GetApplicatByMail(email);

						MailInfoDto mailInfoDto = new MailInfoDto();

						mailInfoDto.sendTo = applicat.Name;
						mailInfoDto.comment = ReplaceComment(comment);

						var body = GetEmailTemplateString(mailInfoDto, "SendMail_EEM.htm");

						this.SendMail(applicat.Email, body); //发mail
					}
				}

				var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
				
				var status = (int)EnumWorkStatus.Pending_QA;
				model.WorkStatus = WorkStatusService.GetWorkStatus(status.ToString());
				model.StatusDate = ToolsHelper.GetTimeZoneNow();
				var userid = Session[ConfigReader.AuthorizeSessionUserID];
				var user = UserManager.GetUser(Int64.Parse(userid.ToString()));
				model.StatusOperator = user;
				model.Operator = user;
				model.CommentCode = CaseReasonService.GetRejectReasonById(CommentCode);
				if (!string.IsNullOrEmpty(comment))
				{
					model.StatusComment = model.StatusComment + "[" + comment + ":" + model.WorkStatus.WorkStatusNameEEM + "]";
				}

				model.InvoiceNo = invoiceNo;

				CaseEEMService.SaveOrUpdateCase(model);

				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
                return Json(new { Success = false, Message = ex.Message }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}

		public ActionResult NextCaseEEM()
		{
			var caseNo = Request["caseNo"];
			var userid = Session[ConfigReader.AuthorizeSessionUserID];
			string nextCaseKeepStatus = Request["NextCaseKeepStatus"];


			var model = CaseEEMService.GetNextGase(Int64.Parse(caseNo), Int64.Parse(userid.ToString()), nextCaseKeepStatus);

			var nextNo = "";

			if (model != null)
			{
				nextNo = model.CaseNo.ToString();
			}
			return Json(new { Success = true, CaseNo = nextNo, NextCaseKeepStatus = nextCaseKeepStatus }, "text/html", JsonRequestBehavior.AllowGet);
		}
		#endregion
		
		
		#region MSD

        public ActionResult ViewTiffEEM()
        {
            string caseNo = Request["caseNo"];
            var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
            ViewData["CaseEEM"] = model;
            var tifBasePath = ConfigurationManager.AppSettings["TifBasePath_View"];
            string file = tifBasePath + model.GetFolerPathEN() + model.FileName + ".tif";
            file = Server.UrlEncode(file);
            string fcontent = "<iframe id='tiffframe'    frameborder='0'  src=' /" + ConfigReader.TiffPage + "?file=" + file + "' style='width:100%;height:100%;'></iframe>";
            ViewData["content"] = fcontent;
            return View("ViewTiffEEM");
        }
		#endregion

		
		//public ActionResult MSDViewTiffPTP()
		//{
		//    string caseNo = Request["caseNo"];
		//    var model = CasePTPService.GetGaseById(Int64.Parse(caseNo));
		//    //var tifBasePath = ConfigurationManager.AppSettings["TifBasePath_View"];
		//    var tifBasePath = ConfigurationManager.AppSettings["TifBasePath"];
		//    string file = tifBasePath + model.GetFolerPathEN() + model.FileName + ".tif";
		//    // string file = Request["file"];
		//    //file = Server.UrlEncode(file);
		//    //string fcontent = "<iframe id='tiffframe'    frameborder='0'  src=' /" + ConfigReader.TiffPage + "?file=" + file + "' style='width:100%;height:100%;'></iframe>";
		//    //ViewData["content"] = fcontent;
		//    //if (ImpersonateLogon.impersonateValidUser(ConfigurationManager.AppSettings["ImpersonateUser"],
		//    //                                     ConfigurationManager.AppSettings["ImpersonateDomain"],
		//    //                                     ConfigurationManager.AppSettings["ImpersonatePassword"]))
		//    //{
		//        FileStream fs = null;
		//        try{
                
		//            fs = System.IO.File.OpenRead(file);
		//            return this.File(fs,"image/tiff");

		//        }
		//        catch(Exception ex){
		//            throw ex;
		//        }
		//        finally{
		//            if (fs != null) {
		//                //fs.Close();
		//            }
		//            //ImpersonateLogon.undoImpersonation();
		//        }
		//   //}
		//   // else
		//   // {
		//   //     throw new Exception("Impersonate Logon Error!");
		//   // }


            
		//    //return View("MSDViewTiff");
		//}


		//public ActionResult MSDViewTiffEEM()
		//{
		//    string caseNo = Request["caseNo"];
		//    var model = CaseEEMService.GetGaseById(Int64.Parse(caseNo));
		//    //var tifBasePath = ConfigurationManager.AppSettings["TifBasePath_View"];
		//    var tifBasePath = ConfigurationManager.AppSettings["TifBasePath"];
		//    string file = tifBasePath + model.GetFolerPathEN() + model.FileName + ".tif";
		//    // string file = Request["file"];
		//    //file = Server.UrlEncode(file);
		//    //string fcontent = "<iframe id='tiffframe'    frameborder='0'  src=' /"+ ConfigReader.TiffPage+"?file=" + file + "' style='width:100%;height:100%;'></iframe>";
		//    //ViewData["content"] = fcontent;
		//    //if (ImpersonateLogon.impersonateValidUser(ConfigurationManager.AppSettings["ImpersonateUser"],
		//    //                         ConfigurationManager.AppSettings["ImpersonateDomain"],
		//    //                         ConfigurationManager.AppSettings["ImpersonatePassword"]))
		//    //{
		//        FileStream fs = null;
		//        try
		//        {

		//            fs = System.IO.File.OpenRead(file);
		//            return this.File(fs, "image/tiff");

		//        }
		//        catch (Exception ex)
		//        {
		//            throw ex;
		//        }
		//        finally
		//        {
		//            if (fs != null)
		//            {
		//                //fs.Close();
		//            }
		//            //ImpersonateLogon.undoImpersonation();
		//        }
		//    //}
		//    //else
		//    //{
		//    //    throw new Exception("Impersonate Logon Error!");
		//    //}
		//    //return View("MSDViewTiff");
		//}

		/// <summary>
		/// mail操作
		/// </summary>
		/// <param name="email"></param>
		private void SendMail(string email,string comment)
		{
			var userid = Session[ConfigReader.AuthorizeSessionUserID];
			var user = UserManager.GetUser(Int64.Parse(userid.ToString()));

			MailHelper webMail = new MailHelper();

            webMail.SendMail(ConfigurationManager.AppSettings["mail.user"],
                            ConfigurationManager.AppSettings["mail.pwd"], 
                            user.Email, new[] { email }, new string[] { }, "MAIL", comment, new string[] { });

		}

		/// <summary>
		/// 获取mail模板内容
		/// </summary>
		/// <param name="mailInfoDto"></param>
		/// <param name="mailTemplate"></param>
		/// <returns></returns>
		public  string GetEmailTemplateString(MailInfoDto mailInfoDto,string mailTemplate)
		{

			VelocityEngine velocity = new VelocityEngine();

			ExtendedProperties props = new ExtendedProperties();
			props.AddProperty("file.resource.loader.path", Server.MapPath("~/EMailTemplate"));
			velocity.Init(props);
			Template template = velocity.GetTemplate(mailTemplate);
			VelocityContext context = new VelocityContext();
			context.Put("MailInfoDto", mailInfoDto);

			StringWriter writer = new StringWriter();
			template.Merge(context, writer);
			return writer.GetStringBuilder().ToString();
		}

		private string GetNextStatus(string status)
		{
			int rasult = 0;
			switch (int.Parse(status))
			{

				case (int)EnumWorkStatus.Distributed:
					{
						rasult = (int)EnumWorkStatus.WaitForCheck;
						break;
					}
				case (int)EnumWorkStatus.WaitForCheck:
					{
						rasult = (int)EnumWorkStatus.Closed;
						break;
					}
				case (int)EnumWorkStatus.Pending_QA:
					{
						rasult = (int)EnumWorkStatus.WaitForCheck;
						break;
					}
			}

			return rasult.ToString();
		}

		private string GetPreviousStatus(string status)
		{
			int rasult = 0;
			switch (int.Parse(status))
			{
				case (int)EnumWorkStatus.WaitForCheck:
					{
						rasult = (int)EnumWorkStatus.Distributed;
						break;
					}
				case (int)EnumWorkStatus.Distributed:
					{
						rasult = (int)EnumWorkStatus.Reject;
						break;
					}
				case (int)EnumWorkStatus.Pending_QA:
					{
						rasult = (int)EnumWorkStatus.Reject;
						break;
					}
			}

			return rasult.ToString();
		}

		public ActionResult GetApplicatList()
		{
			var applicats = ApplicatService.GetApplicatList();
			applicats.Insert(0, new Applicat() { ID = "", Name = Global.pleaseSelect });
			return Json(applicats, "text/plain", JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public ActionResult GetApplicatMail()
		{
			var userId = Request["userId"];
			var isid = Request["ISID"];

			ApplicatQueryDto applicatQueryDto = new ApplicatQueryDto();

			applicatQueryDto.Id = userId;
			applicatQueryDto.ISID = isid;

			if(String.IsNullOrEmpty(userId)&&String.IsNullOrEmpty(isid))
			{
				return Json(new { Success = true, mail = "" }, "text/html", JsonRequestBehavior.AllowGet);

			}
			var applicats = ApplicatService.GetApplicatByDto(applicatQueryDto);
			//applicats.Insert(0, new Applicat() { ID = "", Name = Global.pleaseSelect });
			var mail = "";
			if (applicats !=null)
			{
				mail = applicats.Email;
			}
			return Json(new { Success = true, mail = mail }, "text/html", JsonRequestBehavior.AllowGet);
		}

		private string ReplaceComment(string temp)
		{
			

			temp = temp.Replace("\n", "<br>");
			temp = temp.Replace(" ", "&nbsp;");

			return temp;
		}

		public ActionResult GetRejectReason(string caseType)
		{
			//string pm = Request["id"];
			//var date = CaseService.GetFolderClass(pm);
			var date = CaseReasonService.GetRejectReason(caseType);

			date.Insert(0, new CaseReason() { Id = "", JpReason = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);

		}

		public ActionResult GetPengdingReason(string caseType)
		{
			//string pm = Request["id"];
			//var date = CaseService.GetFolderClass(pm);
			var date = CaseReasonService.GetPengdingReason(caseType);

			date.Insert(0, new CaseReason() { Id = "", JpReason = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);

		}

		public ActionResult GetPayments(string caseType)
		{
			var date = PaymentService.GetPaymentList(caseType);
			date.Insert(0, new Payment() { PaymentId = "", PaymentName = Global.pleaseSelect });
			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);

		}
	}
}
